<template>
  <section class="f-goods">
    <div class="w-card my-content-box" v-if="!isDetail">
      <div class="title-box">
        <span class="title-text">套餐商品列表</span>
        <el-button type="primary" plain @click="pageJump('/goodsManage/mealGoods/add')">+ 新增套餐商品</el-button>
      </div>

      <div class="my-search-box">
        <div>
          <span>商品名称：</span>
          <el-input v-model="searchForm.goodsName" clearable placeholder="请输入商品名称" />
        </div>
        <div>
          <span>购买方式：</span>
          <el-select v-model="searchForm.buyType" clearable>
            <el-option label="金额购买" value="1" />
            <el-option label="积分兑换" value="2" />
          </el-select>
        </div>
        <div>
          <span>设备状态：</span>
          <el-select v-model="searchForm.shelveStatus" clearable>
            <el-option label="上架中" value="1" />
            <el-option label="已下架" value="0" />
          </el-select>
        </div>
        <div class="f-ml-20">
          <el-button @click="searchHandle" type="primary">查询</el-button>
          <el-button @click="resetHandle">重置</el-button>
        </div>
        <!-- <div>
          <span>设备型号：</span>
          <el-input v-model="searchForm.goodsName" clearable placeholder="请输入商品名称" />
        </div> -->
      </div>

      <div class="my-table-box">
        <el-table :height="tableHeight" :header-cell-style="{background:'#d6dee5',color:'#000000',fontSize:'14px'}"
          :cell-style="{fontSize:'12px',color:'#7b7b7d'}" :data="tableData" stripe @selection-change="selectionChange">
          <!-- <el-table-column type="selection" width="55" /> -->
          <el-table-column type="index" width="55" label="序号" align="center" />
          <el-table-column prop="sortPower" label="商品排序" align="center" width="80">
            <template v-slot="scope">
              {{ scope.row.sortPower }}
            </template>
          </el-table-column>
          <el-table-column prop="goodsId" label="商品ID" align="center">
            <template v-slot="scope">
              <el-link style="font-size:12px" type="primary" @click="pageJump('/goodsManage/mealGoods/detail',scope.row.goodsId)">
                {{ scope.row.goodsId || '' }}
              </el-link>
            </template>
          </el-table-column>
          <el-table-column prop="goodsName" label="商品名称" align="center">
            <template v-slot="scope">
              {{ scope.row.goodsName || '--' }}
            </template>
          </el-table-column>
          <el-table-column prop="baseNum" label="商品数量" align="center" width="80">
            <template v-slot="scope">
              {{ scope.row.baseNum }}
            </template>
          </el-table-column>
          <el-table-column prop="showPrice" label="标价（元）" align="center">
            <template v-slot="scope">
              {{ scope.row.showPrice || '--' }}
            </template>
          </el-table-column>
          <el-table-column prop="actualPrice" label="售价（元）" align="center">
            <template v-slot="scope">
              {{ scope.row.actualPrice || '--' }}
            </template>
          </el-table-column>
          <el-table-column prop="buyType" label="购买方式" align="center">
            <template v-slot="scope">
              {{ buyType[scope.row.buyType] }}
            </template>
          </el-table-column>
          <el-table-column prop="buyNumMax" label="购买上限" align="center">
            <template v-slot="scope">
              {{scope.row.buyNumMax }}
            </template>
          </el-table-column>
          <el-table-column label="积分信息" align="left">
            <template v-slot="scope">
              <div v-if="scope.row.buyType == 2">
                <p>购买积分：{{ scope.row.buyPoints }}</p>
                <p>兑换对象：{{ scope.row.pointsBuyFromtype == 1? '平台': scope.row.pointsBuyFromtype == 2? '其他': ''}}</p>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="采购信息" align="left">
            <template v-slot="scope">
              <div v-if="scope.row.buyType == 1">
                <p>采购等级：{{ scope.row.vipLevel }}级</p>
                <p>有效期：{{ scope.row.monthExpire }}月</p>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="shelveStatus" label="设备状态" align="center">
            <template v-slot="scope">
              <p :style="{color:  scope.row.shelveStatus == 1? '#67C23A': '#F56C6C'}">
                {{ scope.row.shelveStatus == 1? '上架中': '已下架' }}
              </p>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" align="center">
            <template v-slot="scope">
              {{ getDateTime(scope.row.createTime)[6] || '--' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="120">
            <template v-slot="scope">
              <div class="table-handle-box">
                <el-link style="font-size:14px" :type="scope.row.shelveStatus == 1? 'danger': 'success'"
                  @click="settingHandle('shelveStatus',scope.row)">
                  {{ scope.row.shelveStatus == 1? '下架': '上架' }}
                </el-link>
                <el-link v-if="scope.row.shelveStatus == 0" style="font-size:14px;margin-left: 20px" type="danger"
                  @click="settingHandle('delete',scope.row)">
                  删除
                </el-link>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div class="my-table-footer">
          <!-- <div class="footer_btn_box">
            <el-button :disabled="chooseList.length == 0" @click="settingHandle('delete')" type="danger" plain>删除</el-button>
          </div> -->
          <el-pagination style="margin-left:auto;" v-model:currentPage="page" v-model:page-size="size"
            :page-sizes="[10, 20, 50, 100]" small :background="true" layout="total, sizes, prev, pager, next, jumper"
            :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </div>

      <!-- 确认密码 -->
      <ConfirmPass ref="confirmPasswordRef" @verification="confirmSuccess" />
    </div>

    <router-view></router-view>
  </section>
</template>

<script>
import { onMounted, reactive, ref, toRefs, watch, nextTick } from 'vue'
import { getWindowWidthAndHeight, warningDeal, getDateTime, successDeal, BlobDownLoad } from '@/utils/utils'
import { useRoute, useRouter } from 'vue-router'
import ConfirmPass from '@/components/confirmPass.vue'
import api from './api'

export default {
  components: { ConfirmPass },

  setup() {
    const route = useRoute()
    const router = useRouter()

    const uploadRef = ref(null)
    const confirmPasswordRef = ref(null)

    const state = reactive({
      isDetail: false,

      searchForm: {
        "buyType": "", // 购买方式，1-金额购买，2-积分兑换，3-都可以，多个用,拼接
        "color": "",
        "equipmentType": "",
        "goodsName": "",
        "orderBy": "id desc",
        "shelveStatus": "", // 状态：1-上架中， 0-已下架
        "wareGoodsId": ""
      },

      tableHeight: 0,
      tableData: [],
      page: 1,
      size: 10,
      total: 0,

      chooseList: [],
      selectData: {},

      buyType: {
        '1': '金额购买',
        '2': '积分兑换',
        '3': '都可以',
      }
    })

    watch(() => route.path, (newVal, oldVal) => {
      setIsDetail()
    })

    function setIsDetail() {
      state.isDetail = (route.path != '/goodsManage/mealGoods')
      getTableData()
    }

    function searchHandle() {
      state.page = 1
      getTableData()
    }

    function resetHandle() {
      state.searchForm = {
        "buyType": "", // 购买方式，1-金额购买，2-积分兑换，3-都可以，多个用,拼接
        "color": "",
        "equipmentType": "",
        "goodsName": "",
        "orderBy": "id desc",
        "shelveStatus": "", // 状态：1-上架中， 0-已下架
        "wareGoodsId": ""
      }
      searchHandle()
    }

    function getTableData() {
      const obj = {
        page: state.page,
        size: state.size,
        ...state.searchForm,
      }
      api.goodsList(obj).then(res => {
        state.tableData = res.data.list
        state.total = res.data.total
      }).catch(err => {
        console.log(err)
      })
    }

    function handleCurrentChange(e) {
      state.page = e
      getTableData()
    }

    function handleSizeChange(e) {
      state.size = e
      getTableData()
    }

    function pageJump(path, goodsId) {
      router.push({
        path,
        query: {
          goodsId
        }
      })
    }

    function settingHandle(type, data) {
      let title = ""
      let msg = ''
      if (type == 'shelveStatus') {
        title = '设备上下架提示'
        msg = `您确定要将所选的商品${data == 1 ? '下架' : '上架'}吗？`
      } else if (type == 'delete') {
        title = '设备删除提示'
        msg = `您确定要将所选的商品删除吗？`
      }
      // if (state.chooseList.length == 0) {
      //   return
      // }
      state.selectData = data
      confirmPasswordRef.value.dialogShow(title, msg, type)
    }

    const confirmSuccess = (type) => {
      if (type == 'shelveStatus') {
        let json = {
          "shelveStatus": state.selectData.shelveStatus == 1 ? 0 : 1,
          "goodsId": state.selectData.goodsId
        }
        api.goodsStatus(json).then(res => {
          successDeal('操作成功！')
          getTableData()
        })
      } else if (type == 'delete') {
        let json = {
          uniqueId: state.selectData.goodsId
        }
        api.goodsDelete(json).then(res => {
          successDeal('操作成功！')
          getTableData()
        })
      }
    }

    function selectionChange(list) {
      state.chooseList = list
    }

    onMounted(() => {
      let winHeight = getWindowWidthAndHeight()
      state.tableHeight = winHeight.windowHeight - 290
      setIsDetail()
    })

    return {
      ...toRefs(state),
      uploadRef,
      confirmPasswordRef,
      getDateTime,
      searchHandle,
      resetHandle,
      handleCurrentChange,
      handleSizeChange,
      settingHandle,
      confirmSuccess,
      selectionChange,
      pageJump,
    }
  }
}
</script>

<style lang="scss" scoped>
.f-goods {
  .my-content-box {
    box-sizing: border-box;
    padding: 20px;

    > .title-box {
      display: flex;
      align-items: center;
      justify-content: space-between;
      .title-text {
        font-size: 16px;
        font-weight: bold;
      }
    }

    .my-search-box {
      box-sizing: border-box;
      padding: 20px 20px 20px 0;
      padding-bottom: 0;
      font-size: 14px;
      display: flex;
      align-items: center;
      gap: 10px;

      > div {
        width: 300px;
        display: flex;
        align-items: center;

        > span {
          flex-shrink: 0;
          width: 90px;
          text-align: right;
        }
      }

      .datebox {
        width: 400px;
      }
    }

    .my-table-box {
      margin-top: 20px;

      .table-handle-box {
        display: flex;
        justify-content: center;
        align-items: center;
      }

      .my-table-footer {
        display: flex;
        align-items: center;
        margin-top: 10px;
        flex-wrap: wrap;
        gap: 10px;
      }
    }
  }
}
</style>